﻿namespace MDXStudio
{
    using Microsoft.AnalysisServices.AdomdClient;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Windows.Forms;

    internal class Context
    {
        private AdomdConnection m_Connection;
        public List<Coordinate> m_Coordinates = new List<Coordinate>();
        private string m_Cube;
        private bool m_fSubcubeCreated;
        public ListView m_ListView;

        public void Clear()
        {
            this.m_Coordinates.Clear();
            this.m_ListView.Items.Clear();
            if (((this.m_Connection != null) && (this.m_Connection.State == ConnectionState.Open)) && this.m_fSubcubeCreated)
            {
                AdomdCommand command = this.m_Connection.CreateCommand();
                command.CommandText = string.Format("DROP SUBCUBE [{0}]", this.m_Cube);
                command.ExecuteNonQuery();
                this.m_Connection = null;
                this.m_Cube = null;
            }
            this.m_fSubcubeCreated = false;
        }

        public void StartContext(AdomdConnection Connection, string cube)
        {
            this.m_Connection = Connection;
            this.m_Cube = cube;
            AdomdCommand command = this.m_Connection.CreateCommand();
            command.CommandText = string.Format("CREATE SUBCUBE [{0}] AS (SELECT Measures.MEMBERS ON 0 FROM [{0}])", this.m_Cube);
            command.ExecuteNonQuery();
            this.m_fSubcubeCreated = true;
        }

        public void UpdateCoordinate(Coordinate c)
        {
            this.m_Coordinates.Add(c);
            ListViewItem item = new ListViewItem(c.Hierarchy.Name);
            item.Tag = c;
            item.SubItems.Add(c.Member.Caption);
            item.EnsureVisible();
            this.m_ListView.Items.Add(item);
        }

        public void UpdateCoordinates(Position tuple, OlapInfoAxis axis)
        {
            AdomdCommand command = this.m_Connection.CreateCommand();
            int count = axis.Hierarchies.Count;
            for (int i = 0; i < count; i++)
            {
                Member m = tuple.Members[i];
                OlapInfoHierarchy h = axis.Hierarchies[i];
                Coordinate c = new Coordinate(h, m);
                this.UpdateCoordinate(c);
                command.CommandText = string.Format("ALTER CUBE [{0}] UPDATE DIMENSION {1}, DEFAULT_MEMBER = {2}", this.m_Cube, h.Name, m.UniqueName);
                command.ExecuteNonQuery();
            }
        }
    }
}

